import { h } from 'vue'
import dayjs from 'dayjs'
import MessageTips from '@/components/message-tips/prompt.vue'

export const openCloseAll = (text, type = 'warning') => {
    ElMessage.closeAll()
}

export const openMessage = (text, type = 'warning') => {
    ElMessage({
        message: text,
        type,
        dangerouslyUseHTMLString: true
    })
}

export const evaluatePassword = (password) => {
    if (password.length < 8) {
        return -1
    }
    var strength = 0
    if (/[a-z]/.test(password)) strength++ // 如果密码包含带有小写字母
    if (/[A-Z]/.test(password)) strength++ // 如果密码包含带有大写字母
    if (/\d/.test(password)) strength++ // 如果密码包含有数字
    if (/[^a-zA-Z0-9]/.test(password)) strength++ // 如果密码包含有特殊字符
    return strength
}



export const reconfirmMessage = (text) => {
    return ElMessageBox({
        message: h(MessageTips, {
            text,
        }),
        customClass: 'reconfirm-message',
        showCancelButton: true,
        showConfirmButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
    })
}

// 对象的深拷贝
export const deepCopy = (obj) => {
    return JSON.parse(JSON.stringify(obj))
}

export const deepClone = (obj) => {
    if (typeof obj !== 'object') return
    let newObj = obj instanceof Array ? [] : {}
    for (let key in obj) {
        if (typeof obj[key] === 'object') {
            newObj[key] = deepClone(obj[key])
        } else {
            newObj[key] = obj[key]
        }
    }
    return newObj
}
// 事件防抖
export const debounce = function (callback, time) {
    let timer = null
    return function () {
        if (timer) clearInterval(timer)
        let self = this
        timer = setTimeout(function () {
            callback.call(self, ...arguments)
        }, time)
    }
}
// 事件节流
export const _throttle = function (fn, wait = 200) {
    let last, timer, now
    return function () {
        now = Date.now()
        if (last && now - last < wait) {
            clearTimeout(timer)
            timer = setTimeout(function () {
                last = now
                fn.call(this, ...arguments)
            }, wait)
        } else {
            last = now
            fn.call(this, ...arguments)
        }
    }
}
// 类型判断
export const getType = (data) => {
    return Object.prototype.toString.call(data).slice(8, -1)
}

// 获取url参数 xxx?yy=zz => {xx:zz} || paramsKey => value
export const getUrlParam = (url, paramsKey) => {
    var result = {}
    if (url.indexOf('?') == -1) return null
    let urlArr = url.split('?')[1].split('&')
    urlArr.forEach((ele) => {
        let arr = ele.split('=')
        result[arr[0]] = arr[1]
    })
    if (paramsKey) return result[paramsKey] || ''
    else return result
}

// 设备信息
export const getEquipmentInfo = () => {
    let userAgent = navigator.userAgent
    const k = ['Android', 'iPhone', 'iPad', 'Mac', 'Windows', 'Linux']
    const data = {
        equipement: k.find((ele) => userAgent.indexOf(ele) !== -1),
        clientWidth: document.body.clientWidth
    }
    return data
}

export const calculater = (date) => {
    const year = date.split('-')[0]
    const month = date.split('-')[1]
    const day = date.split('-')[2]
    const birthDayTime = new Date(date).getTime()
    const nowTime = new Date().getTime()
    const zodiac = {
        0: '猴',
        1: '鸡',
        2: '狗',
        3: '猪',
        4: '鼠',
        5: '牛',
        6: '虎',
        7: '兔',
        8: '龙',
        9: '蛇',
        10: '马',
        11: '羊'
    }

    const constellation = '魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯'.substr(
        month * 2 - (day < '102223444433'.charAt(month - 1) - -19) * 2,
        2
    )
    return {
        constellation,
        zodiac: zodiac[year % 12] || '',
        age:
            Math.floor((nowTime - birthDayTime) / 31536000000) > 0
                ? Math.floor((nowTime - birthDayTime) / 31536000000)
                : 1
    }
}

/**
 *
 * @param {*} records - 数组数据
 * @param {*} oldId - 上级id
 * @returns - 返回树形菜单chidren
 */
const getChilds = (records, oldId) => {
    let childs = []
    records.forEach((val) => {
        oldId === val.parentId && childs.push({ ...val })
    })
    childs.forEach((childNode) => {
        let currNode = getChilds(records, childNode.oldId)
        currNode.length > 0 && (childNode.children = currNode)
    })
    return childs
}
/**
 *顶层节点依据: 传入的rootId为顶层节点，数据的parentId为rootId的时候，说明该条数据是顶层节点的下一层
 * @param {Array} records - 数组数据
 * @param {string} rootId - 根节点id
 * @returns {Array} 返回结果数据
 */
export const formTreeByParentId = (records, rootId) => {
    var result = []
    records.forEach((val) => {
        if (val.parentId === rootId) {
            let parent = { ...val }
            parent.children = getChilds(records, val.oldId)
            result.push(parent)
        }
    })
    return result
}

/**
 * 时间戳转年月日
 * @param {string} date - 需要修改的时间
 * @param {string} format - 格式
 * @param {string} delimiter - 分隔线
 * @returns {string} 返回结果数据
 */
export const dateConvert = (date, format, delimiter) => {
    let str1 = format ? format : ['M', 'D', 'Y']
    let str2 = delimiter ? delimiter : '/'
    let newDate = new Date(date)
    let Y = newDate.getFullYear()
    let M = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1
    let D = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate()
    let value = ''
    str1.forEach((item, i) => {
        if (item == 'Y') {
            value += Y
        }
        if (item == 'M') {
            value += M
        }
        if (item == 'D') {
            value += D
        }
        if (i < 2) {
            value += str2
        }
    })
    return value
}

export const dateDiff = (sDate1, sDate2) => {
    let aDate, oDate1, oDate2, iDays
    aDate = sDate1.split('-')
    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2006格式
    aDate = sDate2.split('-')
    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
    return iDays
}

export const submitAllForm = (refList) => {
    let list = []
    refList.forEach((ele) => {
        list.push(checkForm(ele))
    })
    return Promise.all(list)
}

const checkForm = (formName) => {
    return new Promise((resolve, reject) => {
        formName.value.validate((valid) => {
            if (valid) {
                resolve()
            } else {
                reject()
                return false
            }
        })
    })
}

// 输入-数字/负数/小数
export const inputNumber = (val, type, num) => {
    // type: 1-负数  2-小数  3-(0-100)  4-小于100的两位小数 6 小于一百且小数位为num
    // num type为小数时，小数点后几位
    let str = String(val)
    if (type == 1) {
        let first = str.charAt(0)
        // str = str.replace(/[^\d]/g, "");
        // 先把非数字的都替换掉，除了数字和.
        str = str.replace(/[^\d\.]/g, '')
        // 必须保证第一个为数字而不是.
        str = str.replace(/^\./g, '')
        // 保证只有出现一个.而没有多个.
        str = str.replace(/\.{2,}/g, '.')
        // 保证.只出现一次，而不能出现两次以上
        str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
        if (first === '-') {
            str = '-' + str
        }
    } else if (type == 2) {
        // 先把非数字的都替换掉，除了数字和.
        str = str.replace(/[^\d\.]/g, '')
        // 必须保证第一个为数字而不是.
        str = str.replace(/^\./g, '')
        // 保证只有出现一个.而没有多个.
        str = str.replace(/\.{2,}/g, '.')
        // 保证.只出现一次，而不能出现两次以上
        str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        if (num) {
            if (num == 3) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
            } else if (num == 4) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/, '$1')
            }
        } else {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
        }
    } else if (type == 3) {
        if (/^([0-9]{1,2}|100)$/.test(str)) {
            str = str
        } else {
            str = ''
        }
    } else if (type == 4) {
        str = str.replace(/[^\d\.]/g, '')
        str = str.replace(/^\./g, '')
        str = str.replace(/\.{2,}/g, '.')
        str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
        if (Number(str) <= 100) {
            str = str
        } else {
            str = ''
        }
    } else if (type == 5) {
    } else if (type == 6) {
        str = str.replace(/[^\d\.]/g, '')
        // 必须保证第一个为数字而不是.
        str = str.replace(/^\./g, '')
        // 保证只有出现一个.而没有多个.
        str = str.replace(/\.{2,}/g, '.')
        // 保证.只出现一次，而不能出现两次以上
        str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        if (num) {
            if (num == 3) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
            } else if (num == 4) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/, '$1')
            } else if (num == 2) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
            } else if (num == 1) {
                str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1')
            }
            if (Number(str) <= 100) {
                str = str
            } else {
                str = ''
            }
        } else {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
        }
    } else {
        str = str.replace(/[^\d]/g, '')
    }
    return str
}

// 验证数字长度
export const numLengthVerify = (val, num) => {
    if (val) {
        val = val + ''
        if (val.length > num) {
            val = val.substring(0, num)
        } else if (val.length < num) {
            val = ''
            openCloseAll()
            openMessage('The input length is limited to ' + num + ' digits')
        }
    } else {
        val = ''
    }
    return val
}

// 计算佣金  type-类型 arr-数组 val-值 strIndex-判断字段 maxNum-最大值 itemIndex-数组下标
export const calculateRatio = (type, arr, val, strIndex, maxNum, itemIndex) => {
    let str = val
    if (str) {
        let mes = ''
        if (type == 1) {
            mes = 'Total team split must less than 100%'
        } else if (type == 2) {
            mes = 'Total team split must less than 100%'
        }
        // 先把非数字的都替换掉，除了数字和.
        str = str.replace(/[^\d\.]/g, '')
        // 必须保证第一个为数字而不是.
        str = str.replace(/^\./g, '')
        // 保证只有出现一个.而没有多个.
        str = str.replace(/\.{2,}/g, '.')
        // 保证.只出现一次，而不能出现两次以上
        str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        if (type == 1) {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
        } else if (type == 2) {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1')
        }
        if (arr.length > 0) {
            let num = 0
            arr.forEach((item, index) => {
                if (itemIndex || itemIndex === 0) {
                    if (index != itemIndex) {
                        num += Number(item[strIndex])
                    }
                } else {
                    num += Number(item[strIndex])
                }
            })
            if (Number(str) + num > maxNum) {
                str = ''
                openCloseAll()
                openMessage(mes)
            }
        } else {
            if (Number(str) > maxNum) {
                str = ''
                openMessage(mes)
            }
        }
    }
    return str
}

// 邮箱
export const emailVerify = (val) => {
    let str = val
    if (str) {
        // let req = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
        let req =
            /^[-A-Za-z0-9~!$%^&*_=+}{\'?]+(\.[-A-Za-z0-9~!$%^&*_=+}{\'?]+)*@([A-Za-z0-9_][-A-Za-z0-9_]*(\.[-A-Za-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|AERO|ARPA|BIZ|COM|COOP|EDU|GOV|INFO|INT|MIL|MUSEUM|NAME|NET|ORG|PRO|TRAVEL|MOBI[A-Za-z][A-Za-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/
        if (req.test(str)) {
            str = str
        } else {
            str = ''
        }
    }
    return str
}

// @blur="data.listingFormData.phone=phoneVerify(data.listingFormData.phone)"
// @blur="data.listingFormData.email=emailVerify(data.listingFormData.email)"
// 手机号
export const phoneVerify = (params) => {
    params = typeof params == 'number' ? `${params}` : params.replace(/ /g, '')
    const str = params.split('').filter((ele) => ele && !isNaN(Number(ele)))
    return str.length < 10
        ? ''
        : `(${str[0]}${str[1]}${str[2]}) ${str[3]}${str[4]}${str[5]}-${str[6]}${str[7]}${str[8]}${str[9]}`
}

// 保留几位小数，整数不保留小数
export const retainDecimal = (val, num) => {
    let str = num ? num : 3
    if (val) {
        val = val + ''
        val = parseFloat(parseFloat(val).toFixed(str))
        val = val.toString()
    } else {
        val = ''
    }
    return val
}

// 金额-替换
export const moneyReplace = (num, max = -1) => {
    if (max !== -1 && num > max) {
        return ''
    }
    if (num >= 1) {
        num = num + ''
        num = num.replace(/\,/g, '')
        // num = parseFloat(num);
        num = parseFloat(parseFloat(num).toFixed(2))
        num = num.toLocaleString()
        let len = 0
        let newValue = num.toString()
        num = newValue
    } else if (num === 0) {
        num = 0
    } else if (num === '0') {
        num = '0'
    } else if (num > 0) {
        num = String(num).replace(/^(.*\..{4}).*$/, '$1')
        return num
    } else if (num < 0) {
        num = String(num).replace(/^(.*\..{4}).*$/, '$1')
        return num
    } else {
        num = ''
    }
    return num
}

export const randomId = (list) => {
    let id = Math.random()
    let index = list.findIndex((ele) => ele.id == id)
    if (index == -1) return id
    else return randomId(list)
}

export const copyText = (text) => {
    var textareaC = document.createElement('textarea')
    textareaC.setAttribute('readonly', 'readonly') //设置只读属性防止手机上弹出软键盘
    textareaC.value = text
    document.body.appendChild(textareaC) //将textarea添加为body子元素
    textareaC.select()
    var res = document.execCommand('copy')
    document.body.removeChild(textareaC) //移除DOM元素
    openMessage('复制成功', 'success')
}

export const getItemByIdInTree = (id, tree) => {
    let res = null
    for (let i = 0; i < tree.length; i++) {
        let ele = tree[i]
        ele.id == id ? (res = ele) : ''
        if (res) break
        if (ele.list.length) {
            res = getItemByIdInTree(id, ele.list)
        }
    }
    return res
}

let colorArr = []

export const rdmRgbColor = (type = 1) => {
    //随机生成RGB颜色
    const arr = []
    for (let i = 0; i < 3; i++) {
        if (type) {
            // 暖色
            arr.push(Math.floor(Math.random() * 128 + 64))
        } else {
            // 亮色
            arr.push(Math.floor(Math.random() * 128 + 128))
        }
    }
    const [r, g, b] = arr
    // rgb颜色
    // var color=`rgb(${r},${g},${b})`;
    // 16进制颜色
    const color = `#${r.toString(16).length > 1 ? r.toString(16) : '0' + r.toString(16)
        }${g.toString(16).length > 1 ? g.toString(16) : '0' + g.toString(16)}${b.toString(16).length > 1 ? b.toString(16) : '0' + b.toString(16)
        }`
    if (colorArr.find((ele) => ele == color)) {
        return rdmRgbColor()
    } else {
        colorArr.push(color)
        return color
    }
}

export const parseColor = (color) => {
    if (!color) return ''
    return (
        'rgb(' +
        parseInt('0x' + color.slice(1, 3)) +
        ',' +
        parseInt('0x' + color.slice(3, 5)) +
        ',' +
        parseInt('0x' + color.slice(5, 7)) +
        ',1)'
    )
}

export const matchPhoneNumber = (params) => {
    params = typeof params == 'number' ? `${params}` : params.replace(/ /g, '')
    const str = params.split('').filter((ele) => ele && !isNaN(Number(ele)))
    return str.length < 10
        ? ''
        : `(${str[0]}${str[1]}${str[2]}) ${str[3]}${str[4]}${str[5]}-${str[6]}${str[7]}${str[8]}${str[9]}`
}

export const getDateYearLater = (params) => {
    return dayjs(params).add('1', 'year').format('MM/DD/YYYY')
}

// 两个日期-月份差
export const reduMonths = (startVal, endVal) => {
    if (startVal && endVal) {
        let minDate = new Date(startVal)
        let minYear = minDate.getFullYear()
        let minMonth = minDate.getMonth() + 1
        let maxDate = new Date(endVal)
        let maxYear = maxDate.getFullYear()
        let maxMonth = maxDate.getMonth() + 1
        return maxYear * 12 + maxMonth - (minYear * 12 + minMonth) + 1
    } else {
        return 0
    }
}

/**
 * templateRevis  canvas 模板替换文字 图片
 * @param {string} photo - 模板图片（需要处理的图片）
 * @param {Array} gathers - 替换集合 列表中的值仅包含下面两种类型 且每种类型的属性全部必填
 *      {
 *        text:'',x:0,y:'',type:'text'
 *      }
 *      {
 *        img:'',x:0,y:0,width:0,height:0,type:'img'
 *      }
 * @param {Object} configs - 配置模板大小 图片大小 值为width 和 height 非必填
 * @resolve {string} promise返回结果为处理后的图片url
 **/

export const templateRevise = (photo, gathers, configs = {}) => {
    const config = Object.assign(configs, {
        width: 500,
        height: 500
    })

    let canvas = document.createElement('canvas')
    canvas.width = config.width
    canvas.height = config.height
    canvas.style.backgroundColor = '#ffffff'
    let ctx = canvas.getContext('2d')

    return new Promise((resolve, reject) => {
        const template = new Image()
        template.src = photo

        let status = 1

        template.onload = function () {
            ctx.drawImage(template, 0, 0, config.width, config.height)
            gathers.forEach((ele) => {
                switch (ele.type) {
                    case 'text':
                        ctx.font = ele.font || '22px small-caps'
                        ctx.fillStyle = ele.fillStyle || '#000000'
                        ctx.fillText(ele.text, ele.x, ele.y)
                        break
                    case 'img':
                        const img = new Image()
                        img.src = ele.img
                        status = 0
                        img.onload = function () {
                            ctx.drawImage(img, ele.x, ele.y, ele.width, ele.height)
                            status = 1
                        }
                        break
                    default:
                        break
                }
            })
            let interval = null
            interval = setInterval(() => {
                if (status) {
                    resolve(canvas.toDataURL())
                    clearInterval(interval)
                }
            }, 500)
        }
    })
}

// contextChange 转换 </#if> 和 <*#if>
export const contextChange = (content) => {
    if (content.includes('&lt;/#if&gt;')) {
        return content.replaceAll('&lt;/#if&gt;', '&lt;*#if&gt;')
    } else if (content.includes('&lt;*#if&gt;')) {
        return content.replaceAll('&lt;*#if&gt;', '&lt;/#if&gt;')
    }
    return content
}

export function clearAllCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
    if (keys) {
        for (var i = keys.length; i--;)
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
}

/**
 * 时间戳转年月日
 * @returns 返回拼接后的时间字符串
 */
export const formatDate = (date) => {
    if (!date) return '无';
    date = new Date(date);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
}

/**
 * 时间戳转年月
 * @returns 返回拼接后的时间字符串
 */
export const formatDateYearAndMonth = (date) => {
    if (!date) return '无';
    date = new Date(date);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    return `${year}-${month}`;
}

/**
 * 获取文件名
 */
export const getFileName = (url) => {
    if (!url) return '';
    return url.split('/').pop();
}


export const getBrowserInfo = () => {
    const width = window.innerWidth;
    const height = window.innerHeight;

    const userAgent = navigator.userAgent;
    let browserName = "Unknown";
    let osName = "Unknown";

    // 检测浏览器类型
    if (userAgent.indexOf("Chrome") > -1) {
        browserName = "Chrome";
    } else if (userAgent.indexOf("Firefox") > -1) {
        browserName = "Firefox";
    } else if (userAgent.indexOf("Safari") > -1) {
        browserName = "Safari";
    } else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
        browserName = "Internet Explorer";
    }

    // 检测操作系统
    if (userAgent.indexOf("Win") > -1) {
        osName = "Windows";
    } else if (userAgent.indexOf("Mac") > -1) {
        osName = "MacOS";
    } else if (userAgent.indexOf("X11") > -1 || userAgent.indexOf("Linux") > -1) {
        osName = "Linux";
    }

    return {
        windowSize: {
            width: width,
            height: height
        },
        browser: browserName,
        os: osName,
        platform: navigator.platform
    };
}


export const mergeData = (originalData, newData) => {
    const { message, list } = originalData;
    const newContent = message ? message + newData.content : newData.content;

    return {
        message: newContent,
        type: 'system',
        list: [...list, newData]
    };
}




export const transformMarkdown = (input) => {
    if (input?.length < 8) return input
    if (!input?.trim()) {
        return "";
    }

    // 处理不完整的开始标签
    if (input.includes('<thi') || input.includes('<thin') || input.includes('<think')) {
        const completeTagIndex = input.indexOf('<think>');
        if (completeTagIndex === -1) {
            return input;
        }
    }

    let currentIndex = 0;
    let result = "";
    let isInThinkBlock = false;

    while (currentIndex < input.length) {
        if (!isInThinkBlock) {
            const startTag = input.indexOf("<think>", currentIndex);

            if (startTag === -1) {
                result += input.slice(currentIndex);
                break;
            }

            result += input.slice(currentIndex, startTag);
            currentIndex = startTag + "<think>".length;

            // 跳过 <think> 后的换行符
            while (currentIndex < input.length &&
                (input[currentIndex] === '\n' || input[currentIndex] === ' ')) {
                currentIndex++;
            }

            isInThinkBlock = true;
            continue;
        }

        // 已经在 think 块内
        const endTag = input.indexOf("</think>", currentIndex);
        if (endTag === -1) {
            // 没有找到结束标签，所有剩余内容都作为引用处理
            const remainingContent = input.slice(currentIndex);
            const lines = remainingContent.split('\n');
            result += lines.map(line => `> ${line}`).join('\n');
            break;
        }

        // 找到结束标签，处理到结束标签前的内容
        const thinkContent = input.slice(currentIndex, endTag);
        const lines = thinkContent.split('\n');

        // 处理代码块
        let inCodeBlock = false;
        result += lines.map(line => {
            if (line.trim().startsWith('```')) {
                inCodeBlock = !inCodeBlock;
                return line;
            }
            return inCodeBlock ? line : `> ${line}`;
        }).join('\n');

        result += '\n\n'; // 在 think 结束后添加两个换行
        currentIndex = endTag + "</think>".length;
        isInThinkBlock = false;
    }

    // 处理连续的换行符，将 \n\n 替换为 \n
    // result = result.replace(/\n\n/g, '\n');
    return result;
}


export const transformMarkdownFlow = (input) => {
    if (input?.length < 8) return input
    if (!input?.trim()) {
        return "";
    }

    // 处理不完整的开始标签
    if (input.includes('<thi') || input.includes('<thin') || input.includes('<think')) {
        const completeTagIndex = input.indexOf('<think>');
        if (completeTagIndex === -1) {
            return input;
        }
    }

    let currentIndex = 0;
    let result = "";
    let isInThinkBlock = false;

    while (currentIndex < input.length) {
        if (!isInThinkBlock) {
            const startTag = input.indexOf("<think>", currentIndex);

            if (startTag === -1) {
                result += input.slice(currentIndex);
                break;
            }

            result += input.slice(currentIndex, startTag);
            currentIndex = startTag + "<think>".length;

            // 跳过 <think> 后的换行符
            while (currentIndex < input.length &&
                (input[currentIndex] === '\n' || input[currentIndex] === ' ')) {
                currentIndex++;
            }

            isInThinkBlock = true;
            continue;
        }

        // 已经在 think 块内
        const endTag = input.indexOf("</think>", currentIndex);
        if (endTag === -1) {
            // 没有找到结束标签，所有剩余内容都作为引用处理
            const remainingContent = input.slice(currentIndex);
            const lines = remainingContent.split('\n');
            result += lines.map(line => `> ${line}`).join('\n');
            break;
        }

        // 找到结束标签，处理到结束标签前的内容
        const thinkContent = input.slice(currentIndex, endTag);
        const lines = thinkContent.split('\n');

        // 处理代码块
        let inCodeBlock = false;
        result += lines.map(line => {
            if (line.trim().startsWith('```')) {
                inCodeBlock = !inCodeBlock;
                return line;
            }
            return inCodeBlock ? line : `> ${line}`;
        }).join('\n');

        result += '\n\n'; // 在 think 结束后添加两个换行
        currentIndex = endTag + "</think>".length;
        isInThinkBlock = false;
    }

    // 处理连续的换行符，将 \n\n 替换为 \n
    // result = result.replace(/\n\n/g, '\n');
    return result;
}


export const splitMarkdownAnswer = (input) => {
    const result = {
        think: '',
        text: ''
    }

    if (!input) return result

    // 找到 think 标签的位置
    const thinkStartIndex = input.indexOf('<think>')
    const thinkEndIndex = input.indexOf('</think>')

    if (thinkStartIndex !== -1 && thinkEndIndex !== -1) {
        // 提取 think 内容并添加引用标记
        const thinkContent = input.slice(thinkStartIndex + '<think>'.length, thinkEndIndex)
        const lines = thinkContent.split('\n')
        result.think = lines.map(line => `> ${line}`).join('\n')

        // 提取 text 内容（不包含 think 标签）
        const beforeThink = input.slice(0, thinkStartIndex)
        const afterThink = input.slice(thinkEndIndex + '</think>'.length)
        result.text = (beforeThink + afterThink).trim()
    } else {
        // 如果没有 think 标签，所有内容都作为 text
        result.text = input
    }

    return result
}


export const isJSON = (str) => {
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
};

/**
 * 转换文件大小
 * @param {number} size - 文件大小（字节）
 * @returns {string} 转换后的文件大小字符串
 */
export const formatFileSize = (size) => {
    if (!size) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let index = 0;
    let fileSize = size;

    while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024;
        index++;
    }

    // 保留两位小数
    return `${fileSize.toFixed(2)} ${units[index]}`;
}

/**
 * 获取文件类型
 * @param {string} fileName - 文件名
 * @returns {string} 文件类型
 */
export const getFileType = (fileName) => {
    if (!fileName) return 'doc';

    // 获取文件扩展名（转换为小写）
    const ext = fileName.split('.').pop().toLowerCase();

    // 定义文件类型映射
    const typeMap = {
        // Excel 文件
        'xlsx': 'xlsx',
        'xls': 'xlsx',
        'csv': 'xlsx',
        // Word 文件
        'doc': 'doc',
        'docx': 'doc',
        // PDF 文件
        'pdf': 'pdf',
        // 文本文件
        'txt': 'text',
        'log': 'text',
        // 图片文件
        'png': 'png',
        'jpg': 'png',
        'jpeg': 'png',
        'gif': 'png',
        'bmp': 'png',
        'webp': 'png'
    };

    return typeMap[ext] || 'doc'; // 默认返回 doc 类型
}



export const download = (res, fileName) => {
    const blob = new Blob([res], { type: res.type })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
    URL.revokeObjectURL(url)
}


// 随机生成0-1
export const random01 = () => {
    return Math.random() < 0.5 ? 0 : 1
}

// 生成随机颜色
const getRandomColor = () => {
    const colors = [
        '#409eff', // 蓝色
        '#67c23a', // 绿色
        '#e6a23c', // 黄色
        '#f56c6c', // 红色
        '#909399', // 灰色
        '#9c27b0', // 紫色
        '#ff9800', // 橙色
        '#2196f3', // 浅蓝色
        '#4caf50', // 深绿色
        '#795548'  // 棕色
    ]
    return colors[Math.floor(Math.random() * colors.length)]
}

// 处理模板文本
export const processTemplate = (template) => {
    const color = getRandomColor()
    return template.replace(/\[(.*?)\]/g, `<span style="color: ${color}; font-weight: 600; padding: 0 2px; background-color: ${color}15; border-radius: 4px; display: inline-block; margin: 0 1px;">$1</span>`)
}
